import csv
import json
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from core.models import StudentProfile
from report.models import Report, BodyType
from pathlib import Path
from django.utils import timezone
from datetime import datetime, timedelta
from django.contrib.auth.hashers import make_password

class Command(BaseCommand):
    help = '初始化报告数据'

    def handle(self, *args, **options):
        base_dir = Path(__file__).resolve().parent.parent.parent.parent
        csv_path = base_dir / 'report_data.csv'

        # 导入用户数据
        with open(csv_path, 'r', encoding='utf-8') as f:
            _reader = csv.DictReader(f)
            for row in _reader:
                try:
                    # 1. 创建用户
                    user_info = {
                        'username': "stu" + row.get('sid'),
                        'password': make_password(row.get('sid')),
                        'is_active': True,
                    }
                    try:
                        user = User.objects.get(username='stu' + row.get('sid'))
                    except User.DoesNotExist:
                        user = User.objects.create(**user_info)
                    # 2. 创建学生账户
                    student_info = {
                        'user': user,
                        'student_id': row.get('sid'),
                        'student_name': row.get('student_name'),
                        'gender': row.get('gender'),
                        'phone_number': '',
                        'major': row.get('major'),
                        'enroll_year': row.get('sid')[:4],
                        'grade': row.get('classname')[:4],
                        'birthday': '',
                        'classname': row.get('classname'),
                    }
                    try:
                        student = StudentProfile.objects.get(student_id=row.get('sid'))
                    except StudentProfile.DoesNotExist:
                        student = StudentProfile.objects.create(**student_info)
                    # 3. 创建报告
                    body_type = BodyType.objects.filter(body_type=row.get('finalCorporeity')).first()
                    dt = datetime.strptime(row.get('createTime'), '%Y-%m-%d %H:%M:%S')  # 假设 createTime 格式为 'YYYY-MM-DD HH:MM:SS'，根据实际情况调整
                    createTime = timezone.make_aware(dt + timedelta(hours=8))
                    info = {
                        "report_id": row.get('id'),
                        "createTime": createTime,
                        "user": user,
                        "age": row.get("age"),
                        "height": row.get("height"),
                        "weight": row.get("weight"),
                        "body_type": body_type,
                        "type_stat": row.get('countDetail'),
                        "faceImg": "/media/report-images/" + row.get('face_image') + ".jpg",
                        "tongueImg": "/media/report-images/" + row.get('tongue_image') + ".jpg",
                    }
                    report = Report.objects.create(**info)
                    self.stdout.write(self.style.SUCCESS(f'CREATE REPORT: {row.get("sid")}'))
                except Exception as e:
                    self.stdout.write(f"{row.get('student_name')}: {str(e)}")
                    continue